package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.domain.StrategyInterest;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.StrategyInterestMapper;
import cn.wolfcode.trip.base.mapper.StrategyMapper;
import cn.wolfcode.trip.base.service.IStrategyInterestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class StrategyInterestServiceImpl implements IStrategyInterestService {
    @Autowired
    private StrategyInterestMapper strategyInterestMapper;
    @Autowired
    private StrategyMapper strategyMapper;

    /**
     * 定义进行点赞的方法
     *
     * @param strategyId
     * @param user
     * @return
     */
    @Override
    public StrategyInterest toByLile(Long strategyId, User user) {
        //用户第一次点赞,获取到游记id
        //创建对象
        StrategyInterest strategyInterest1 = strategyInterestMapper.selectByStrategyIdAndUserId(strategyId, user.getId());
        StrategyInterest strategyInterest = new StrategyInterest();
        if (strategyInterest1 == null) {
            strategyInterest.setUser(user);
            //添加攻略id
            Strategy strategy = strategyMapper.selectByPrimaryKey(strategyId);
            //将得到我的攻略信息添加到strategyInterest中
            strategyInterest.setStrategy(strategy);
            //添加点赞信息
            strategyInterest.setTime(new Date());
            strategyInterestMapper.insert(strategyInterest);
            //在点赞的信息表中,添加点赞次数,查询到点赞的次数
            int likenum = strategyMapper.selectByLike(strategyId);
            //在点赞表中添加
            strategyMapper.addStrategyId(strategyId, (likenum + 1));
        } else {
            //取消点赞功能
            int likenum = strategyMapper.selectByLike(strategyId);
            strategyMapper.updateByLikenum((likenum - 1), strategyId);
        }
        StrategyInterest strategyInterest2 = strategyInterestMapper.selectByPrimaryKey(strategyId, user.getId());
        return strategyInterest2;
    }

    @Override
    public StrategyInterest selectStrategyId(Long strategyId, User user) {
        StrategyInterest strategyInterest = strategyInterestMapper.selectByPrimaryKey(strategyId, user.getId());
        //进行查询操作,判断用户是否已经添加了点赞操作
        if (strategyInterest != null) {
            throw new RuntimeException("对象为不为空,有点赞");
        }
        return strategyInterest;
    }
}
